<?php
namespace app\erp_meixingtiyu\controller;

use app\common\library\wechat\WxPay;
use app\common\model\Wxapp as WxappModel;
use app\mxty\model\BookingFragment as BookingFragmentModel;
use app\store\controller\Controller as StoreController;
use think\facade\Request;
use app\erp_meixingtiyu\model\Booking as BookingModel;
use app\erp_meixingtiyu\logic\Booking as BookingLogic;

class Booking extends StoreController
{
    /**
     * 强制验证当前访问的控制器方法method
     * 例: [ 'login' => 'POST' ]
     * @var array
     */
    protected $methodRules = [
        'operateBooking' => 'POST',
    ];

    // 管理员后台操作预订
    public function operateBooking()
    {
        $params = Request::only([
            'arena',
            'arena_id',
            'betweenTime',
            'fragments',
            'fragments_str',
            'maximum',
            'minimum',
            'continuity',
            'arena_part',
            'part_id',
            'price',
            'remark',
            'status',
            'book',
            'part_time_fragment_ids'
        ]);

        $user_id = $this->store['user']['store_user_id'];
        $result = (new BookingLogic())->addBooking($params, $user_id);
        return $this->renderSuccess(['result' => $result], '操作成功');
    }

    // 获取后台管理操作订场记录分页列表
    public function operateList()
    {
      $list = (new BookingModel())->getListWithAdmin();
      return $this->renderSuccess(compact('list'), 'success');
    }


    // 获取前台用户订场记录分页列表
    public function bookingList()
    {
      $list = (new BookingModel())->getListWithUser();
      return $this->renderSuccess(compact('list'), 'success');
    }

    // 根据日期范围获取前台预订记录
    public function bookingListFilter($dateArr)
    {
      $list = (new BookingLogic())->getListByDate($dateArr);
      return $this->renderSuccess($list, 'success');
    }

    //退款
    public function refund($order_no = null){
        $model = (new \app\mxty\logic\Booking())->getOrderByNo($order_no);
        $bookingFragmentModel = new BookingFragmentModel;
        $list = $bookingFragmentModel::where('booking_id', $model -> id)->select();

        $wxConfig = WxappModel::getWxappCache(getStoreId());
        $WxPay = new WxPay($wxConfig);
        $WxPay->refund($model ->transaction_id, $model ->total_price, $model ->total_price);

        //退款
        $model ->pay_status = 30;
        $model -> save();
        foreach($list as $key=>$booking){
            $bookingFragmentModel::update(['pay_status' => 30], ['id' => $booking -> id]);
        }

        return $this->renderSuccess();

    }

}
